package com.easy.mq.entry;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
	  private static ObjectMapper mapper = new ObjectMapper();  
	  
	    public static <T> String bean2Json(T obj) { 
	    	try {
	    		if(obj == null) {
	    			return null;
	    		}
	    		return mapper.writeValueAsString(obj); 
	    	}catch(IOException e) {
	    		e.printStackTrace();
	    		return null;
	    	}
	    }  
	  
	    public static <T> T json2Bean(String jsonStr, Class<T> objClass)  
	          {  
	        try {
	        	if(StringUtils.isEmpty(jsonStr)) {
	        		return null;
	        	}
				return mapper.readValue(jsonStr, objClass);
			} catch ( IOException e) {
				e.printStackTrace();
				return null;
			} 
	    }  
	    
	    public static <T>  String list2Json(List<T> list) {
	    	try {
	    		if(list == null) {
	    			return null;
	    		}
	    		return mapper.writeValueAsString(list); 
	    	}catch(IOException e) {
	    		e.printStackTrace();
	    		return null;
	    	}
		}
	    
	    public static <T> List<T>   json2List(String jsonStr,Class<T> beanClass){
	    	JavaType javaType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, beanClass);  
	    	try {
	    		if(StringUtils.isEmpty(jsonStr)) {
	        		return null;
	        	}
				List<T> list =  mapper.readValue(jsonStr, javaType);
				return list;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}   
		}
	    
	    
	    public static <T> List<T>   json2List(String jsonStr,List<T> beanClass){
	    	try {
	    		if(StringUtils.isEmpty(jsonStr)) {
	        		return null;
	        	}
				@SuppressWarnings("unchecked")
				List<T> list =  mapper.readValue(jsonStr, beanClass.getClass());
				return list;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}   
		}
	    
	    public static <T> T json2Bean(String jsonStr,String subKey,Class<T> objClass){
	    	 JsonNode rootNode;
			try {
				rootNode = mapper.readTree(jsonStr);
				JsonNode treekey2value = rootNode.findPath(subKey);
				return json2Bean(treekey2value.toString(), objClass);
			} catch (IOException e) {
				e.printStackTrace();
			}  
			return null;
	    }
	    
	    public static String getJson(String jsonStr,String subKey){
	    	 JsonNode rootNode;
			try {
				rootNode = mapper.readTree(jsonStr);
				JsonNode treekey2value = rootNode.findPath(subKey);
				return String.valueOf(treekey2value.asText());
			} catch (IOException e) {
				e.printStackTrace();
			}  
			return null;
	    }
}
